<?php

/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2017/6/8
 * Time: 下午2:16
 */
namespace Mq\Core;

use Mq\Base\Facade;
use Pimple\Container;

class Application extends Container implements Facade
{

    /**
     * 基础任务providers
     * @var array
     */
    protected static $baseJobProvider = [];

    /**
     * 基础任务实例
     * @var array
     */
    protected static $baseJobInstance = [];

    /**
     * 保存APP实例
     * @var null
     */
    private static $_instance = null;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();

        //注册基础任务providers
        $this->registerBaseJobProvider();
    }

    /**
     * 获取Application实例
     * @return Application
     */
    public static function getInstance()
    {
        if (!isset(self::$_instance) || !(self::$_instance instanceof self)) {
            self::$_instance = new self;
        }

        return self::$_instance;
    }

    /**
     * 注册基础任务服务
     * param $abstract
     * param $alias
     * @return bool
     */
    protected function registerBaseJobProvider()
    {
        //获取任务别名
        $aliases = AliasLoader::getInstance()->getAliases();

        if (!empty($aliases)) {
            foreach ($aliases as $abstract => $aliase) {
                $this->bindingJobProvider($abstract, $aliase);
            }
        }

        return true;
    }

    /**
     * 注册任务服务
     * @param $abstract
     * @param $alias
     * @return bool
     */
    public function registerJobProvider($abstract, $alias)
    {
        if (!isset(static::$baseJobProvider[$abstract])) {
            static::$baseJobProvider[$abstract] = $alias;
        }

        $this->bindingJobProvider($abstract, $alias);

        return true;
    }

    /**
     * 绑定任务
     * @param $abstract
     * @param $alias
     * @return bool
     */
    public function bindingJobProvider($abstract, $alias)
    {
        if (!isset(static::$baseJobInstance[$abstract]) || !is_object(static::$baseJobInstance[$abstract])) {
            static::$baseJobInstance[$abstract] = new $alias;
        }

        return true;
    }

    /**
     * 获取任务实例
     * @param $abstract
     * @return null
     */
    public function getJobInstance($abstract)
    {
        return isset(static::$baseJobInstance[$abstract]) ? static::$baseJobInstance[$abstract] : null;
    }

    /**
     * 获取任务服务
     * @param $abstract
     * @return null
     */
    public function getJobProvider($abstract)
    {
        return isset(static::$baseJobProvider[$abstract]) ? static::$baseJobProvider[$abstract] : null;
    }
}